#!/usr/bin/env python
# coding:utf-8
import sys
import time
import smtplib
from email.mime.text import MIMEText
from email.header import Header
#使用第三方SMTP服务器发送邮件
def send_mail(address,sub,email_text):
    '''
    :address 收件人
    :param sub: 邮件主题
    :param email_text: 邮件内容
    :return:
    '''
    mail_host = 'smtp.exmail.qq.com'
    mail_user = 'xuyanbin@gpai.net'
    mail_passd = 'H5aSgq4p3MkV9ni8'
    sender = 'xuyanbin@gpai.net'
    message = MIMEText(email_text,'plain','utf-8')  #邮件内容
    message['From'] = Header(mail_user,'utf-8')     #设置邮件的发件人
    message['To'] = Header(address,'utf-8')         #设置邮件的收件人
    subject = sub                                    #邮件主题
    receivers = [address,]                           #接收邮箱
    message['Subject'] = Header(subject,'utf-8')
    try:
        smtpObj = smtplib.SMTP('')
        smtpObj.connect(mail_host,25)
        smtpObj.login(mail_user,mail_passd)
        smtpObj.sendmail(sender,receivers,message.as_string())
        file = open('/var/log/zabbix/email.log', 'a+')
#        print ('邮件发送成功.\n')
        file.write(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        file.write('\n')
        file.write('邮件发送成功.\n')
        file.write('-----------------end----------------------------')
    except smtplib.SMTPException :
#        print ('Error:无法发送邮件.\n')
        file.write('邮件发送失败.\n')
    finally:
        file.close()
if __name__ == '__main__':
    if len(sys.argv)>3:
        send_mail(sys.argv[1],sys.argv[2],sys.argv[3])
#    else:
#        print('执行脚本请输入正确的参数，第一个参数为收件人，第二个参数为邮件主题，第三个为邮件正文')
#        file = open('/var/log/zabbix/email.log', 'a+')
#        file.write('脚本参数不正确.\n')
#        file.close()
